package the_eleven_chapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.sun.corba.se.spi.activation.Server;

public class ServerThread extends Thread {

	// 保存与本线程相关的Socket对象
	Socket socket = null;
	// 保存本线程的客户计数
	int clientNum;

	public ServerThread(Socket socket, int clientNum) {
		this.socket = socket;
		this.clientNum = clientNum + 1;
	}

	@Override
	public void run() {
		try {
			String line;
			// 由Socket对象得到输入流，并构造相应的BufferedReader对象
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 由Socket对象得到输出流，并构造PrintWriter对象
			PrintWriter os = new PrintWriter(socket.getOutputStream());
			// 由系统标准输入设备构造BufferedReader对象
			BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
			// 在标准输出上打印从客户端读入的字符串
			System.out.println("Client: " + clientNum + is.readLine());
			// 从标准输入读入一字符串
			line = sin.readLine();
			// 如果该字符串为bye,则停止循环
			while (!line.equals("bye")) {
				// 向客户端输出该字符串
				os.println(line);
				// 刷新输出流，使Client马上收到该字符串
				os.flush();
				// 在系统标准输出上打印该字符串
				System.out.println("Server: " + line);
				// 从Client读入一字符串，并打印到标准输出上
				System.out.println("Client: " + clientNum + is.read());
				// 从系统标准输入读入一字符串
				line = sin.readLine();
			}
			os.close();
			is.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
